//两两交换链表中的节点
//https://leetcode.cn/problems/swap-nodes-in-pairs/description/
public class Test {
    public static void main(String[] args) {
        //
    }
}


//Definition for singly-linked list.
class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }

class Solution {
    /*public ListNode swapPairs(ListNode head) {
        //
        ListNode prev = new ListNode();
        prev.next = head;
        ListNode cur = head;
        ListNode next = cur.next;
        ListNode nnext = cur.next.next;
        head = next;
        while (nnext.next!=null && nnext.next.next != null) {
            //进行交换
            prev.next = next;
            next.next = cur;
            cur.next = nnext;

            //进行移动
            prev = cur;
            cur = nnext;
            next = nnext.next;

        }
        //进行交换
        prev.next = next;
        next.next = cur;
        cur.next = nnext;
        return head;
    }*/
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;

        ListNode newHead = new ListNode();
        newHead.next = head;

        ListNode prev = newHead;
        //prev.next = head;//这句好像有点问题
        ListNode cur = head;
        ListNode next = head.next;
        ListNode nnext = head.next.next;
        while (cur != null && next != null) {
            //交换节点
            prev.next = next;
            next.next = cur;
            cur.next = nnext;

            //修改指针
            prev = cur;//注意顺序
            cur = nnext;
            //为了解决空指针问题，这里可以这样处理
            /*next = nnext;
            nnext = nnext.next.next;*/
            if(cur != null) next = cur.next;
            if(next != null) nnext = next.next;

        }
        return newHead.next;

    }
}

